package com.levi.distributedlimiter.config;

import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.zookeeper.ZookeeperDataSource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 把流控规则持久化到zookeeper
 */
@Component
public class ZookeeperDataSourceConfig {

    @Value("${zookeeper.address}")
    private String remoteAddress;

    @Value("${zookeeper.path}")
    private String path;

    @Bean
    public void loadRules() {

//        final String remoteAddress = "121.5.123.44:2181";
//        final String path = "/sentinel-dashboard/sentinel-flow-rules";

        ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<>(remoteAddress, path,
                source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
                }));
        FlowRuleManager.register2Property(flowRuleDataSource.getProperty());


    }
}
